//
//  OutsideGoodsDetailVC.m
//  yunbaolive
//
//  Created by ybRRR on 2020/5/27.
//  Copyright © 2020 cat. All rights reserved.
//

#import "OutsideGoodsDetailVC.h"
#import "JCHATConversationViewController.h"
#import "CommodityDetailModel.h"
#import "OutsideHeadCell.h"
#import "CommodityCell2Row1.h"
#import "CommodityCell2Row2.h"
#import "CommodityCell3.h"
#import "ShopDetailVC.h"
#import "GuaranteeView.h"
#import "ShareGoodsAlert.h"

@interface OutsideGoodsDetailVC ()<UITableViewDelegate, UITableViewDataSource,goshopDelegate>
{
    UIButton *isCollectBtn;

}
@property (nonatomic, strong)CommodityDetailModel *commodityModel;
@property (nonatomic, strong)UITableView *commodityTable;
@property (nonatomic, strong)GuaranteeView *guarView;

@end

@implementation OutsideGoodsDetailVC

- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

#pragma mark ----添加商品访问记录------
-(void)addGoodsVisit{
    
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken],@"goodsid":self.goodsID, @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"goodsid":self.goodsID,
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign
                          };
    [WYNetworking postWithUrl:@"Buyer.addGoodsVisitRecord" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            
        }else{
            if (code!=1001) {
                [MBProgressHUD showError:msg];
            }

        }

        } Fail:^(id fail) {
            
        }];

}
#pragma mark----获取商品详情------
-(void)getGoodInfo{
    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"goodsid":self.goodsID,
                          };
    [WYNetworking postWithUrl:@"Shop.getGoodsInfo" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            self.commodityModel = [CommodityDetailModel modelWithDictionary:[info firstObject]];
            [self.commodityTable reloadData];
            if ([self.commodityModel.iscollect isEqual:@"1"]) {
                [isCollectBtn setImage:[UIImage imageNamed:getImagename(@"commodity_收藏亮")] forState:0];
            }else{
                [isCollectBtn setImage:[UIImage imageNamed:getImagename(@"commodity_收藏")] forState:0];
            }

        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
        }];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([self.fromWhere isEqual:@"seller"]) {
        self.titleL.text = YZMsg(@"预览商品");
    }else{
        self.titleL.text = YZMsg(@"商品详情");
        [self addGoodsVisit];

    }
    self.subNavi.backgroundColor = UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
    self.naviLine.hidden = NO;
    self.naviLine.backgroundColor = RGB(245, 245, 245);

    self.rightBtn.hidden = NO;
    [self.rightBtn setImage:[UIImage imageNamed:@"goods_share"] forState:0];

    [self.view addSubview:self.commodityTable];
    [self createBottom];
    [self getGoodInfo];

}
-(void)clickNaviRightBtn
{
    ShareGoodsAlert *alert = [[ShareGoodsAlert alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height) andGoodsModel:self.commodityModel];
    [self.view addSubview:alert];

}

-(UITableView *)commodityTable{
    if (!_commodityTable) {
        _commodityTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 64+statusbarHeight, _window_width, _window_height-64-statusbarHeight-60-ShowDiff) style:UITableViewStylePlain];
        _commodityTable.delegate = self;
        _commodityTable.dataSource = self;
        _commodityTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _commodityTable.estimatedRowHeight = 0;
        _commodityTable.estimatedSectionHeaderHeight = 0;
        _commodityTable.estimatedSectionFooterHeight = 0;
    }
    return _commodityTable;
}
#pragma mark-------UITableviewDelegate--------------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 505;
    }else if(indexPath.section == 1){
        return 45;
    }else{
        return 170;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 5)];
    footer.backgroundColor = RGB(250, 250, 250);
    return footer;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        OutsideHeadCell *cell1 = [[OutsideHeadCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell1"];
        cell1.model = self.commodityModel;
        cell1.selectionStyle = UITableViewCellSelectionStyleNone;
        cell1.contentView.backgroundColor = UIColor.clearColor;
        cell1.backgroundColor = UIColor.clearColor;
        return cell1;
    }else if(indexPath.section == 1){
        CommodityCell2Row2 *row2 = [[NSBundle mainBundle]loadNibNamed:@"CommodityCell2Row2" owner:self options:nil].firstObject;
        return row2;
    }else{
        CommodityCell3 *cell3 = [[CommodityCell3 alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell3"];
        cell3.model = self.commodityModel;
        cell3.delegate = self;
        return cell3;

    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([self.fromWhere isEqual:@"seller"]) {
        [MBProgressHUD showError:YZMsg(@"预览不支持该功能")];
        return;
    }

    YBWeakSelf;
    if(indexPath.section == 1){
        if ([self.commodityModel.goods_status isEqual:@"-1"]){
            [MBProgressHUD showError:YZMsg(@"商品已下架")];
            return;
        }

            if (_guarView) {
                [_guarView removeFromSuperview];
                _guarView = nil;
            }
            _guarView = [[NSBundle mainBundle]loadNibNamed:@"GuaranteeView" owner:self options:nil].firstObject;
            _guarView.frame = CGRectMake(0, 0, _window_width, _window_height);
            _guarView.hideEvent = ^{
                [weakSelf.guarView removeFromSuperview];
                weakSelf.guarView = nil;
            };
            [self.view addSubview:_guarView];
    }
}

#pragma mark------添加底部按钮---------
-(void)createBottom{
    UIView *bottomBack = [[UIView alloc]init];
    bottomBack.frame = CGRectMake(0, _window_height-60-ShowDiff, _window_width, 60+ShowDiff);
    bottomBack.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomBack];
    
    [PublicObj lineViewWithFrame:CGRectMake(0, 0, _window_width, 1) andColor:RGB(240, 240, 240) andView:bottomBack];
    NSArray *arr = @[@"店铺",@"客服",@"收藏",@"立即购买"];
    NSArray *arrTitle = @[YZMsg(@"店铺"),YZMsg(@"客服"),YZMsg(@"收藏"),YZMsg(@"立即购买")];
    for (int i = 0; i < arr.count; i ++) {
        if ( i < 3) {
            UIButton *btn = [UIButton buttonWithType:0];
            btn.frame = CGRectMake(i * _window_width *0.2, 0, _window_width *0.2, 60);
            NSString *langStr = @"";
            if ([lagType isEqual:EN]) {
                langStr = [common getLanguage];
            }
            [btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"commodity_%@%@",arr[i],langStr]] forState:0];
            btn.tag = 100000+i;
            [btn addTarget:self action:@selector(bottomBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [bottomBack addSubview:btn];
            if (i == 2) {
                isCollectBtn = btn;
            }

        }else{
            UIButton *btn = [UIButton buttonWithType:0];
            btn.frame = CGRectMake( _window_width *0.6, 0, _window_width *0.4, 60);
            [btn setTitle:arrTitle[i] forState:0];
            [btn setTitleColor:[UIColor whiteColor] forState:0];
            btn.titleLabel.font = [UIFont systemFontOfSize:14];
            btn.tag = 100000+i;
            [btn addTarget:self action:@selector(bottomBtnClick:) forControlEvents:UIControlEventTouchUpInside];

            [btn setBackgroundColor:Pink_Cor];
            [bottomBack addSubview:btn];
        }
    }
}
-(void)bottomBtnClick:(UIButton *)sender{
    if ([self.fromWhere isEqual:@"seller"]) {
        [MBProgressHUD showError:YZMsg(@"预览不支持该功能")];
        return;
    }

    switch (sender.tag) {
        case 100000:
            if ([self.commodityModel.goods_status isEqual:@"-1"]){
                [MBProgressHUD showError:YZMsg(@"商品已下架")];
                return;
            }

            [self goshopClick];
            break;
        case 100001:{
            if ([self.commodityModel.goods_status isEqual:@"-1"]){
                [MBProgressHUD showError:YZMsg(@"商品已下架")];
                return;
            }

            NSDictionary *userDic = @{
                @"id":self.commodityModel.shop_uid,
                @"user_nickname":self.commodityModel.shop_name,
                @"avatar":self.commodityModel.shop_avatar,
            };
            [[YBMessageManager shareManager] chatWithUser:userDic];
        }
            break;
        case 100002:{
            [self collectionGoods];

        }
            break;
        case 100003:{
            if ([self.commodityModel.goods_status isEqual:@"-1"]){
                [MBProgressHUD showError:YZMsg(@"商品已下架")];
                return;
            }

            //立即购买
            [self showBuyAlert];
        }
            break;
        default:
            break;
    }
}
-(void)collectionGoods{

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"goodsid":self.goodsID
                          };
    [WYNetworking postWithUrl:@"Shop.setCollect" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            NSDictionary *infos = [info firstObject];
            NSString *iscollect = minstr([infos valueForKey:@"iscollect"]);
            if ([iscollect isEqual:@"1"]) {
                [isCollectBtn setImage:[UIImage imageNamed:getImagename(@"commodity_收藏亮")] forState:0];
                [MBProgressHUD showError:YZMsg(@"已收藏")];
            }else{
                [isCollectBtn setImage:[UIImage imageNamed:getImagename(@"commodity_收藏")] forState:0];
                [MBProgressHUD showError:YZMsg(@"已取消收藏")];
            }
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
        }];


}

-(void)showBuyAlert{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:YZMsg(@"提示") message:YZMsg(@"此商品属于站外链接商品,可能存在一定风险,请谨慎购买") preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:YZMsg(@"取消") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:YZMsg(@"继续购买") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:self.commodityModel.href]];
    }];
    //修改title
    NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:YZMsg(@"提示")];
    [alertControllerStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, 2)];
    [alert setValue:alertControllerStr forKey:@"attributedTitle"];

    [cancel setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
    [sure setValue:Pink_Cor forKey:@"_titleTextColor"];
    [alert addAction:cancel];
    [alert addAction:sure];
    [self presentViewController:alert animated:YES completion:nil];
    
}
#pragma mark--------店铺主页-----------
-(void)goshopClick
{
    if ([self.fromWhere isEqual:@"seller"]) {
        [MBProgressHUD showError:YZMsg(@"预览不支持该功能")];
        return;
    }
    ShopDetailVC *vc = [[ShopDetailVC alloc]init];
    vc.toUserID = minstr([self.commodityModel.shop_info valueForKey:@"uid"]);
    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:vc animated:YES];

}


@end
